import tkinter as tk
from tkinter import ttk, messagebox

from 实体类.User import User
from 工具包utils.str_operation import get_user_object
from 数据库操作.LoginMysql import LoginMysql

class AuthWindow(tk.Tk):
    """认证窗口（登录/注册）"""

    def __init__(self):
        super().__init__()
        self.result_object = None
        self.title("用户认证")
        self.geometry("300x200")
        self.resizable(False, False)
        self.show_login_frame()


    def clear_window(self):
        """清除当前所有控件"""
        for widget in self.winfo_children():
            widget.destroy()

    def create_login_form(self):
        """创建登录表单"""
        frame = ttk.Frame(self)

        # 表单元素
        ttk.Label(frame, text="用户名:").grid(row=0, column=0, padx=5, pady=5)
        self.login_username = ttk.Entry(frame)
        self.login_username.grid(row=0, column=1, padx=5, pady=5)

        ttk.Label(frame, text="密码:").grid(row=1, column=0, padx=5, pady=5)
        self.login_password = ttk.Entry(frame, show="*")
        self.login_password.grid(row=1, column=1, padx=5, pady=5)

        ttk.Button(frame, text="登录", command=self.login).grid(row=4, column=0, sticky=tk.E, padx=3)
        ttk.Button(frame, text="注册账号", command=self.show_register_frame).grid(row=4, column=1, sticky=tk.E, padx=5)

        return frame

    def create_register_form(self):
        """创建注册表单"""
        frame = ttk.Frame(self)

        # 表单元素
        ttk.Label(frame, text="新用户名:").grid(row=0, column=0, padx=5, pady=5)
        self.reg_username = ttk.Entry(frame)
        self.reg_username.grid(row=0, column=1, padx=5, pady=5)

        ttk.Label(frame, text="新密码:").grid(row=1, column=0, padx=5, pady=5)
        self.reg_password = ttk.Entry(frame, show="*")
        self.reg_password.grid(row=1, column=1, padx=5, pady=5)

        ttk.Label(frame, text="性别:").grid(row=2, column=0, padx=5, pady=5)
        self.reg_gender = ttk.Frame(frame)
        self.reg_gender.grid(row=2, column=1, padx=5, pady=5, sticky=tk.W)

        self.gender_var = tk.StringVar(value="男")
        ttk.Radiobutton(self.reg_gender, text="男", variable=self.gender_var, value="男").pack(side=tk.LEFT)
        ttk.Radiobutton(self.reg_gender, text="女", variable=self.gender_var, value="女").pack(side=tk.LEFT)

        ttk.Label(frame, text="年龄:").grid(row=3, column=0, padx=5, pady=5)
        self.reg_age = ttk.Entry(frame)
        self.reg_age.grid(row=3, column=1, padx=5, pady=5)

        ttk.Button(frame, text="注册", command=self.register_user).grid(row=4, column=0, sticky=tk.E, padx=3)
        ttk.Button(frame, text="返回登录", command=self.show_login_frame).grid(row=4, column=1, sticky=tk.E, padx=5)

        return frame

    def show_login_frame(self):
        """显示登录界面"""
        self.clear_window()
        self.login_frame = self.create_login_form()
        self.login_frame.pack(pady=20)

    def show_register_frame(self):
        """显示注册界面"""
        self.clear_window()
        self.register_frame = self.create_register_form()
        self.register_frame.pack(pady=20)

    def login(self):
        """登录验证"""
        username = self.login_username.get()
        password = self.login_password.get()

        result_data = LoginMysql().select_username_password(username, password)
        result = LoginMysql().judge(username, password)

        self.result_object = get_user_object(result_data)

        if not username or not password:
            messagebox.showerror("错误", "请输入用户名和密码")
            return

        if result > 0:
            messagebox.showinfo("成功", "登录成功！")
            self.destroy()
            from GUI界面.MainApplication import MainApplication
            MainApplication(self.result_object)  # 启动主界面
        else:
            messagebox.showerror("错误", "用户名或密码错误")

    def register_user(self):
        """用户注册"""
        user = User(self.reg_username.get(),
                    self.reg_password.get(),
                    self.reg_age.get(),
                    self.gender_var.get()
        )

        result = LoginMysql().select_username(user.username)

        if not user.username or not user.password:
            messagebox.showerror("错误", "请输入用户名和密码")
            return

        if result > 0:
            messagebox.showerror("错误", "用户名已存在")
            return

        if len(user.password) < 4:
            messagebox.showerror("错误", "密码至少需要4位")
            return

        LoginMysql().insert_information(user.username,
                                        user.password,
                                        user.age,
                                        user.gender
        )
        messagebox.showinfo("成功", "注册成功！")
        self.show_login_frame()

if __name__ == "__main__":
    try:
        auth_window = AuthWindow()
        auth_window.mainloop()
    except Exception as e:
        print("发生异常：", e)